package com.cdream.basic.thread.manage;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * @author cdream
 * @date 2021/9/19
 */
public class OneShotLatch {

    private final Sync sync = new Sync();

    private void signal() {
        sync.releaseShared(0);
    }

    private void await() {
        sync.acquireShared(0);
    }

    private class Sync extends AbstractQueuedSynchronizer {
        @Override
        protected int tryAcquireShared(int arg) {
            return getState() == 1 ? 1 : -1;
        }

        @Override
        protected boolean tryReleaseShared(int arg) {
            setState(1);
            return true;
        }
    }
}
